﻿using System;
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using Agile.Service;
using Agile.Service.Rbac;

namespace ConsoleApp {
    /// <summary>
    /// 采集系统页面 id="NF-"开头的命令
    /// </summary>
    public class HrCollectionPageButtons:Strategy {
        public override int Sid { get; set; } = 3;
        public override string Name { get; set; } = "开始采集人事系统页面命令";

        private static readonly IMenuElementService menuElementDal = new MenuElementService();
        private static readonly IMenuService menuDal = new MenuService(new MenuElementService());
        private static string baseUrl = "http://localhost:8085";
        public override void RunCode(object data) {
            Run();
        }
        public static void Run() {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("*******开始采集人事系统页面命令***************");
            CollectionPageButtons();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("*******采集人事系统页面命令结束***************");
        }
        private static void CollectionPageButtons() {
            var menus = menuDal.FindAll("Name NOT IN('系统结构','健康检查','图标管理') AND ParentID<>'00000000-0000-0000-0000-000000000000'");
            foreach(var menu in menus) {
                var uri = menu.Url.Split("/");
                if(uri.Length <= 1) continue;
                string testContent = GetPageContent(baseUrl + menu.Url);
                if(!string.IsNullOrWhiteSpace(testContent)) {
                    // <a\b[^>]+\bid="NF-([^"]*)"[^>]*>([\s\S]*?)</a>
                    string pattern = @"<a\b[^>]+\bid=""NF-([^""]*)""[^>]*>([\s\S]*?)</a>";
                    Regex s = new Regex(pattern);
                    if(s.IsMatch(testContent)) {
                        foreach(Match item in s.Matches(testContent)) {
                            //<a id="NF-add" authorize="yes" class="btn btn-primary dropdown-text" onclick="AddBatch()"><i class="glyphicon glyphicon-plus"></i>新增</a>
                            string tempstr = item.Groups[0].Value;
                            MenuElement pageButton = new MenuElement();
                            pageButton.ModuleId = menu.ID;
                            pageButton.Name = Utils.GetChineseWord(tempstr);
                            pageButton.DomId = GetBtnInfo(tempstr,@"id=.+?""","id=");
                            pageButton.Icon = GetBtnInfo(tempstr,@"<i\b[^>]+\bclass=.+?""","<i").Replace("class=","");
                            pageButton.Script = GetBtnInfo(tempstr,@"onclick=.+?""","onclick=");

                            var flg = menuElementDal.Exists(p => p.Name == pageButton.Name && p.ModuleId == menu.ID);
                            if(!flg) {
                                menuElementDal.Add(pageButton);
                                Console.WriteLine("***" + pageButton.ToString());
                            }
                        }
                    }
                }
            }
        }
        private static string GetBtnInfo(string m_outstr,string pattern,string filter = "") {
            string tempstr = "";
            Regex s = new Regex(pattern);
            if(s.IsMatch(m_outstr)) {
                foreach(Match item in s.Matches(m_outstr)) {
                    tempstr = item.Groups[0].Value;
                    tempstr = tempstr.Replace(@"""","");
                    tempstr = tempstr.Replace(filter,"");
                    break;
                }
            }
            return tempstr;
        }
        private static string GetPageContent(string url) {
            try {
                //登录 /Login/index?sinOut=true
                var client = new WebClientHelper();
                client.BaseAddress = baseUrl;
                string srcString = client.PostData("/Login/CheckLogin","username=admin&password=admin&code=admin");
                string pageHtml = client.DownloadString(url);
                return getFirstNchar(pageHtml);
            } catch(Exception ex) {
                try {
                    WebClient myClient = new WebClient();
                    myClient.BaseAddress = baseUrl;
                    myClient.Credentials = CredentialCache.DefaultCredentials;
                    var pageData = myClient.DownloadData(url);
                    string pageHtml = Encoding.Default.GetString(pageData);
                    return getFirstNchar(pageHtml);
                } catch(Exception ex1) {
                    Logger.LogError("WebClient:" + ex.Message,ex1);
                    return string.Empty;
                }
            }
        }
        /// <summary>
        /// 此私有方法从一段HTML文本中提取出一定字数的纯文本
        /// </summary>
        /// <param name="instr">HTML代码</param>
        /// <returns>纯文本</returns>
        private static string getFirstNchar(string instr) {
            string m_outstr = instr.Clone() as string;
            m_outstr = new Regex(@"(?m)<script[^>]*>(\w|\W)*?</script[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"(?m)<style[^>]*>(\w|\W)*?</style[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"(?m)<link[^>]*>(\w|\W)*?[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"<iframe[\s\S]+</iframe *>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"<frameset[\s\S]+</frameset  *>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"-->",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"<!--.*",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"(&nbsp;)+").Replace(m_outstr,"");
            m_outstr = new Regex(@"(\r\n\r\n)+").Replace(m_outstr,"");

            return m_outstr;
        }
    }
}
